package com.lyl.async.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@EnableAsync
@Configuration
public class AsyncConfig {
    //核心线程数
    public static final int CORE_POOL_SIZE = 5;
    //最大线程数
    public static final int MAX_POOL_SIZE = 20;
    //队列的容量
    public static final int QUEUE_CAPACITY = 50;
    //空闲线程的存活时间
    public static final int KEEP_ALIVE_SECONDS = 60;
    //线程的名称前缀
    public static final String THREAD_NAME_PREFIX = "localThreadPool";

    @Bean("localTaskExecutor")
    public ThreadPoolTaskExecutor localTaskExecutor(){
        log.info("线程池开始初始化");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数
        executor.setCorePoolSize(CORE_POOL_SIZE);
        //最大线程数
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        //队列容量
        executor.setQueueCapacity(QUEUE_CAPACITY);
        //非核心线程没有任务之后的存活时间
        executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        //线程池中没有线程可用时的拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //线程前缀
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        //进行初始化
        executor.initialize();
        log.info("线程池初始化完毕");
        return executor;
    }


}
